<script type="text/javascript"> 
function ShoppingCartController (aRefreshPricesPostingUrl, aRemovePhotoFromCartPostingUrl, aCreateCheckoutPostingUrl, i18nMessages){
	
	var shoppingCart = new ShoppingCart();

	var ELEMENT_NAME_PREFIX = "photo";
		
	var AMOUNT_COPIES= "amountCopies"
	var AMOUNT_COPIES_CLASS= "."+AMOUNT_COPIES;
		
	var counter = 0;
	
	var SIZE= "tamano"
	var SIZE_CLASS= "."+SIZE;
	
	var PAPER_TYPE= "papel"
	var PAPER_TYPE_CLASS= "."+PAPER_TYPE;
	
	var PAPER_BORDER= "borde"
	var PAPER_BORDER_CLASS= "."+PAPER_BORDER;
	
	var DEFECT= "defecto";
	var DEFECT_CLASS= "."+DEFECT;
	
	var NON_DEFECT= "manual";
	var NON_DEFECT_CLASS= "."+NON_DEFECT;
	
	var ERROR= "error";
	var ERROR_CLASS= "."+ERROR;
	
	var ROW= "rowItem";
	var ROW_CLASS= "."+ROW;
	
	var REFERENCE= "referencia";
	var REFERENCE_CLASS= "."+REFERENCE;
	
	var DEFECT_CHECKBOX_IDENTIFIER = "defectCheck";
	var DEFECT_CHECKBOX_IDENTIFIER_CLASS= "."+DEFECT_CHECKBOX_IDENTIFIER;
	
	var DELETE_BUTTON_IDENTIFIER = "deleteButton";
	var DELETE_BUTTON_IDENTIFIER_CLASS= "."+DELETE_BUTTON_IDENTIFIER;
	
	var COPY_BUTTON_IDENTIFIER = "copyButton";
	var COPY_BUTTON_IDENTIFIER_CLASS= "."+COPY_BUTTON_IDENTIFIER;
	
	var COPY_BUTTON_APPENDIX_IDENTIFIER = "copyButtonAppendix";
	var COPY_BUTTON_APPENDIX_IDENTIFIER_CLASS= "."+COPY_BUTTON_APPENDIX_IDENTIFIER;
	
	var allPhotosContainer = jQuery('#allPhotosContainer');
	var defectConfigurationContainer = jQuery('#defectContainer');
	
	var photographersContainer = jQuery('#photographerSelectionContainer');
	var photographersSelectBox = jQuery('#photographerSelect');
	
	var priceInputElement =  jQuery('#txt_orderPrice');
	var totalCopiesInputElement =  jQuery('#txt_totalCopies');
	var minOrderPriceInputElement =  jQuery('#txt_minPrice');
	
	var orderButtonElement =  jQuery('#btnOrder');
	
	var noPhotosInCart = jQuery('#noPhotosInCart');
	
	var refreshPricesPostingUrl = aRefreshPricesPostingUrl;
	var removePhotoFromCartPostingUrl = aRemovePhotoFromCartPostingUrl;
	var createCheckoutPostingUrl = aCreateCheckoutPostingUrl;
	
	var i18nMessages = i18nMessages;

	var minOrderPrice = parseFloat(minOrderPriceInputElement.val());

	this.addPhotos = addPhotos;
	this.addSizes = addSizes;
	this.addPaperBorders = addPaperBorders;
	this.addPaperTypes = addPaperTypes;
	this.initDefectContainer = initDefectContainer; 
	//this.emptyShoppingCart = emptyShoppingCart;
	this.refreshPrices = refreshPrices;	
	this.fillOrder = fillOrder;
	this.getDefectCheckBoxIdFirstImage = getDefectCheckBoxIdFirstImage; 
	this.getAddNewCopyIdFirstImage = getAddNewCopyIdFirstImage;
	
	
	function addPhotos(aJSONPhotoList){
		jQuery.each(aJSONPhotoList, function (){			
			addPhoto(this);		
		});	
		setAlternateRowStyle();
		refreshPrices();
		setValidator();
	}
	
	function addSizes(aJSONSizesList){
		jQuery.each(aJSONSizesList, function (){			
			shoppingCart.addSize(new Size(this.width,this.height,this.id));
		});
					
	}
	
	function addPaperBorders(aJSONBordersList){
		jQuery.each(aJSONBordersList, function (){			
			shoppingCart.addPaperBorder(new PaperBorder(this.description,this.id));
		});
					
	}
	
	function addPaperTypes(aJSONTypesList){
		jQuery.each(aJSONTypesList, function (){			
			shoppingCart.addPaperType(new PaperBorder(this.description,this.id));
		});
					
	}
				
	function initDefectContainer(){
		var defectProperties = 	createDefectProperties();
			
		//Tamaño
		var sizeField = defectProperties.find(SIZE_CLASS);
		sizeField.addClass(REFERENCE);
		sizeField.removeClass(DEFECT_CLASS);		
		sizeField.change(function (event) {					
			var newValue = jQuery(this).val();									
			allPhotosContainer.find(SIZE_CLASS+DEFECT_CLASS).val(newValue);			
		});	
		
		//Tipo papel
		var field = defectProperties.find(PAPER_TYPE_CLASS);
		field.addClass(REFERENCE);
		field.removeClass(DEFECT_CLASS);		
		field.change(function (event) {					
			var newValue = jQuery(this).val();									
			allPhotosContainer.find(PAPER_TYPE_CLASS+DEFECT_CLASS).val(newValue);			
		});	
		
		//Borde
		var field = defectProperties.find(PAPER_BORDER_CLASS);
		field.addClass(REFERENCE);
		field.removeClass(DEFECT_CLASS);		
		field.change(function (event) {					
			var newValue = jQuery(this).val();									
			allPhotosContainer.find(PAPER_BORDER_CLASS+DEFECT_CLASS).val(newValue);			
		});
		
		defectProperties.find(':input').change(function(){
			refreshPrices();
		});
			
		defectConfigurationContainer.append(defectProperties);		
	}
	
	/*
	function initMercadoPago(){
		orderAndBuyButtonElement.click(function(){			
			createCheckoutUrl();
		});
	}
	initMercadoPago();
	*/
	
	function createPhotoProperties(){
		var divContainer = jQuery('<div  >');
		var divLeftContainer = jQuery('<div class="form-horizontal span4" >');
		divLeftContainer.append(createDefectCheckboxField());
		divLeftContainer.append(createPhotosAmountField());			
		divLeftContainer.append(createPhotosSizesField());
		
		
		var divRightContainer = jQuery('<div class="form-horizontal span4"> ');
		
		divRightContainer.append(createPhotosPapersField());
		divRightContainer.append(createPhotosBordersField());		
		divRightContainer.append(createDeleteButtonField());
		
		divContainer.append(divLeftContainer);
		divContainer.append(divRightContainer);
		return divContainer;
	}
	
	function createDefectProperties(){
		var divContainer = jQuery('<div class="form-horizontal span5">');			
		divContainer.append(createPhotosSizesDefectField());
						
		var paperControl = createPhotosPapersField();
		var tooltipPaper = jQuery('<img src="${resource(dir:'images', file: 'question_icon_s.png')}" data-toggle="modal" data-target="#matteGlossyModal"> ');
		paperControl.find('.controls').append(tooltipPaper);		
		divContainer.append(paperControl);
		
		var borderControl = createPhotosBordersField();
		var tooltipControl = jQuery('<img src="${resource(dir:'images', file: 'question_icon_s.png')}"  data-toggle="modal" data-target="#borderModal"> ');
		borderControl.find('.controls').append(tooltipControl);
		divContainer.append(borderControl);
		return divContainer;
	}
	
	function addPhoto(photoJSONObject){					
		var elementName = ELEMENT_NAME_PREFIX + photoJSONObject.photoId;				
		var photoEntity = new Photo(photoJSONObject.photoId,photoJSONObject.url,elementName,photoJSONObject.thumbnailUrl,photoJSONObject.thumbnailMediumUrl);
		shoppingCart.addPhotoToCart(photoEntity);		
		
		//Genero la estructura de dom
		var aRowContainer = jQuery('<div class="row '+ROW+'" name="'+photoEntity.getId()+'"  />');		
		
		//Columna Imagen 			
		var aPhotoContainer = jQuery('<div class="span3 listPhotoItem '+elementName+'" />'); 					  
		var galleryRef = jQuery('<a rel="gallery" class="preview" href="'+photoEntity.getUrl()+'" />');		
		var image = jQuery('<img src="'+photoEntity.getThumbnailMediumUrl()+'" class="img-rounded" >');				
		
		galleryRef.append(image);											  				
		aPhotoContainer.append(galleryRef);			
				
		aRowContainer.append(aPhotoContainer);		
		
		//Columna propiedades
		var photoPropertiesPanel = createPhotoProperties();
											
		aRowContainer.append(photoPropertiesPanel);
		
		// La inicio en configuracion por defecto
		setDefectConfigurationOnRow(aRowContainer);	
		
			
		// Le agrego los botones de copiar y eliminar la foto				
		//aRowContainer.append(getButtonsColumn(aRowContainer));
		
		//Agrego toda la fila.	
		allPhotosContainer.append(aRowContainer);
		
		
		//Agrego el manejo de eventos
		addButtonEvents(aRowContainer);								
	}
		
	function addButtonEvents(newRow){
	
		// Evento asociado al cambio de estado de check!
		var check = newRow.find(DEFECT_CHECKBOX_IDENTIFIER_CLASS);
		check.click(function () {					
			
			var parentRow = jQuery(this).parents(ROW_CLASS);
			if (jQuery(this).is(':checked')){							
				setDefectConfigurationOnRow(parentRow);
			}
			else{				
				setNonDefectConfigurationOnRow(parentRow);
			}
			
		});
		
		// Evento asociado a borrar la foto
		var deleteButton = newRow.find(DELETE_BUTTON_IDENTIFIER_CLASS);
		deleteButton.click( function (){
			
			//Veo si se debe eliminar del cart en el servidor (solo si no existen otras copias de la foto en el cart)
			
			var photoId = newRow.attr('name');
			
			if (jQuery('[name="'+photoId+'"]').size() == 1){
				//Esta borrando la ultima copia, por lo tanto la saca del cart
				removePhotoFromCart(photoId);								           								 
			}

			//Lo elimino en la vista
			//primero lo vacio por un tema de performance
			newRow.empty();
			newRow.remove();
			setAlternateRowStyle();			
			refreshPrices();
		});
		
		// Evento asociado a clonar la foto
		var copyButton = newRow.find(COPY_BUTTON_IDENTIFIER_CLASS);
		copyButton.click( function (){
			
			//Solo la clona si no tiene errores
			if (newRow.find(ERROR_CLASS).size() == 0){
				var rowCopy = newRow.clone()
				
				//Le cambio el id al campo de texto.
				rowCopy.find(AMOUNT_COPIES_CLASS).prop('id','photos'+getCounter());
				
				rowCopy.insertAfter(newRow);
				addButtonEvents(rowCopy);			
				setAlternateRowStyle();
				refreshPrices();
				
				setValidator()	
			}
			
		});
		
		jQuery(newRow).find(':input').change(function(){
			refreshPrices();
		});
		
		imagePreview();
	}
	
	
	
	function setDefectConfigurationOnRow(aRowContainer){
		aRowContainer.find(NON_DEFECT_CLASS).each( function(){
			jQuery(this).removeClass(NON_DEFECT);
			jQuery(this).addClass(DEFECT);
			jQuery(this).prop('disabled',true);
		});
		
		//Reestablezco los valores por defecto
		//aRowContainer.find(AMOUNT_COPIES_CLASS).val(jQuery(AMOUNT_COPIES_CLASS+REFERENCE_CLASS).val());
		aRowContainer.find(SIZE_CLASS).val(jQuery(SIZE_CLASS+REFERENCE_CLASS).val());
		aRowContainer.find(PAPER_TYPE_CLASS).val(jQuery(PAPER_TYPE_CLASS+REFERENCE_CLASS).val());
		aRowContainer.find(PAPER_BORDER_CLASS).val(jQuery(PAPER_BORDER_CLASS+REFERENCE_CLASS).val());
	}
	
	function setNonDefectConfigurationOnRow(aRowContainer){
		aRowContainer.find(DEFECT_CLASS).each( function(){
			jQuery(this).removeClass(DEFECT);
			jQuery(this).addClass(NON_DEFECT);
			jQuery(this).prop('disabled',false);
		});
	}
	
	function setAlternateRowStyle(){
		var current = 0;
		allPhotosContainer.find(ROW_CLASS).each( function() {
			var aRowContainer = jQuery(this)
			aRowContainer.removeClass("unpairRowItem");
			aRowContainer.removeClass("pairRowItem");
			aRowContainer.addClass(current % 2 == 0 ? "pairRowItem" : "unpairRowItem" );
			current++;			
		});
	}
	
	function removePhotoFromCart(photoId){
		jQuery.ajax({
            url: aRemovePhotoFromCartPostingUrl,
            data: { "photoId":  photoId },
            datatype:"json",
            type: "POST",            
            async:true,		  
            success: function(data){
            	//Se analiza si se debe cambiar la imagen del cart en la pantalla superior.        		
            	setCartToolBarVisibility(data.photosStillInCart);             
            },          	
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });	
	}
	
	
	// Fields que se ven en las rows.			
	
	function createPhotosAmountField(){					
		var amountPhotosValue = jQuery('<input id="photos'+getCounter()+'" maxlength="4"  type="text" value="1" class="input-small requiredNumber '+AMOUNT_COPIES+'">');		
		
		return createGenericField(i18nMessages['cart.copies'], amountPhotosValue);				
	}
	
	function getCounter(){		
		return ++counter; 
	}
	
	function createPhotosSizesField(){	
		var valueContainer = jQuery('<div >');
		//Le agrego el boton para copiar.
		valueContainer.append(createAvailableSizesSelectBox());		
		valueContainer.append('<div class="fl '+COPY_BUTTON_IDENTIFIER+'">');
		valueContainer.append('<div class="fl '+COPY_BUTTON_APPENDIX_IDENTIFIER+'" style="padding-left:130px">');
		return createGenericField(i18nMessages['cart.size'],valueContainer)
	}	
	
	function createPhotosSizesDefectField(){			
		return createGenericField(i18nMessages['cart.size'],createAvailableSizesSelectBox());
	}			
		
	
	function createAvailableSizesSelectBox(){
		var sel = $('<select class="input-small fl '+SIZE+' '+NON_DEFECT+'" />');						
		jQuery.each(shoppingCart.getSizes(),function() {			
		 	sel.append($("<option>").attr('value', this.getId()).text(this.getHeight()+"x"+this.getWidth()));
		});
		return sel;
	}	
	
	function createAvailablePaperTypeSelectBox(){
		var sel = $('<select class="span2 '+PAPER_TYPE+' '+NON_DEFECT+'" />');						
		jQuery.each(shoppingCart.getPaperTypes(),function() {			
		 	sel.append($("<option>").attr('value', this.getId()).text(this.getDescription()));
		});
		return sel;
	}
	
	function createPhotosBordersField(){		
		return createGenericField(i18nMessages['cart.border'],createAvailablePaperBorderSelectBox())
	}
	
	function createPhotosPapersField(){
		return createGenericField(i18nMessages['cart.paper'],createAvailablePaperTypeSelectBox())
	}
	
		
	function createAvailablePaperBorderSelectBox(){
		var sel = $('<select class="span2 '+PAPER_BORDER+' '+NON_DEFECT+'" />');						
		jQuery.each(shoppingCart.getPaperBorders(),function() {			
		 	sel.append($("<option>").attr('value', this.getId()).text(this.getDescription()));
		});
		return sel;
	}
	
	
	function createDefectCheckboxField(){				
		var checkLabel= jQuery('<label class="checkbox" /> ');
		//var check = jQuery('<input type="checkbox" id="'+ +'" class="'+DEFECT_CHECKBOX_IDENTIFIER+'" checked >');				
		var check = jQuery('<input type="checkbox" class="'+DEFECT_CHECKBOX_IDENTIFIER+'" checked >');
		checkLabel.append(check);
		checkLabel.append(i18nMessages['cart.configuration.default2']);		
		return createGenericField("",checkLabel)
	}
	
	function createDeleteButtonField(){				
		var value = jQuery('<button class="btn btn-danger delete '+DELETE_BUTTON_IDENTIFIER+'"> <span>'+i18nMessages['delete']+'</span> </button>');				
		return createGenericField("",value)				
	}
	
	// Armo una estructura del siguiente tipo
	/*
	<form class="form-horizontal">
		<div class="control-group">
			<label class="control-label" for="inputEmail">Email</label>
			<div class="controls">
				<input type="text" id="inputEmail" placeholder="Email">
			</div>
		</div>
	</form>
	*/	
	function createGenericField(label, valueElement){
		//Agrego el tamaño por defecto
		var container =  jQuery('<div class="control-group">');
		var label= jQuery('<label class="control-label">'+label+'</label>');
		var valueContainer =  jQuery('<div class="controls" >');
		var value = valueElement;
		
		valueContainer.append(value);
		container.append(label);
		container.append(valueContainer);
		return container;
	}
	
	function createOrderItems(){
		var rows = jQuery(ROW_CLASS);

		var orderItems = [];
		var totalAmountCopies = 0
		//Itero a traves de cada row.
		rows.each( function (){
						
			var photoId = jQuery(this).attr('name');			
			
			//Recupero el size asociado
			var size = jQuery(this).find(SIZE_CLASS).val();						
			
			var amountCopies = jQuery(this).find(AMOUNT_COPIES_CLASS).val();
			totalAmountCopies += parseInt(amountCopies);
			
			var paperType = jQuery(this).find(PAPER_TYPE_CLASS).val();
			
			var paperBorder = jQuery(this).find(PAPER_BORDER_CLASS).val();
			
			var orderItem = new OrderItem(photoId,amountCopies,size,paperBorder,paperType);
			
			orderItems.push(orderItem);						
			
		});		
		
		totalCopiesInputElement.val(totalAmountCopies);
		
		return orderItems;
	}

	function refreshPrices(){	
		var orderItems = createOrderItems();
		
		jQuery.ajax({
            url: refreshPricesPostingUrl,
            data: { "order": JSON.stringify(orderItems) },
            datatype:"json",
            type: "POST",            
            async:true,		                
            success: function(data){
            	// Se actualiza el valor el precio
            	priceInputElement.val(data.replace("\"",""));
            	
            	// Se analiza si se esta superando al minimo de la orden. 
            	var currentPrice = parseFloat(priceInputElement.val());
            	
            	
            	var amountPhotos = jQuery(ROW_CLASS).length;
			            	
            	//Se analiza si hay fotos y el precio excede al precio minimo 	            	
            	if (currentPrice >= minOrderPrice && amountPhotos > 0 ) {
            		minOrderPriceInputElement.css('color','black');            		
            		orderButtonElement.prop('disabled',false)
            	}
            	else if (currentPrice < minOrderPrice ){
            		minOrderPriceInputElement.css('color','red');            		
            		disableOrderPossibility();
            	}
            	else 
            		disableOrderPossibility();
            	
            	
            },
            error: function(){		                		                				       
            	alert("Failure");		                   
            }	                
        });	
	}
	
	function disableOrderPossibility(){				
		orderButtonElement.prop('disabled',true);
	}
	
	function fillOrder(){		
		var orderItems = createOrderItems();
		jQuery('#order').val(JSON.stringify(orderItems));		
	}	
	
	function setValidator(){		
		//Seteo los CSS Class en el validador para que actuen segun su validacion
        jQuery.validator.addClassRules({
            'requiredNumber': {
                required: true,                    
                integer:true
            }

        });

        jQuery.validator.addMethod('integer', function(value, element, param) {
            var regexp = /^\d+$/                
            return (regexp.test(value));
        },  i18nMessages['cart.format.incorrect']);   
        
        jQuery.extend($.validator.messages, {
            required: i18nMessages['cart.field.required'],
            date: i18nMessages['cart.date.invalid'],
            email: i18nMessages['cart.email.invalid'],
            url: i18nMessages['cart.url.invalid'],
            number: i18nMessages['cart.number.invalid']
        });

        // Inicio el plugin            
      	jQuery('#allPhotosContainerForm').validate();
      	
	}
	
	function getDefectCheckBoxIdFirstImage(){
		var firstImage = getFirstImage();
		var check = firstImage.find('.checkbox');  		
		
		if (check != undefined){
			check.prop('id',"firstCheck");
		return check.prop('id');
		}	
		else 
			return null;
	}
	
	function getAddNewCopyIdFirstImage(){
		var firstImage = getFirstImage();
		var check = firstImage.find(COPY_BUTTON_APPENDIX_IDENTIFIER_CLASS);  	
		if (check != undefined){
			check.prop('id',"firstNewCopy");
			return check.prop('id');
		}	
		else 
			return null;
		
	}
	
	function getFirstImage(){
		return allPhotosContainer.children().first();
	}
	
	function setCartToolBarVisibility(photosInCart){
		jQuery('#cartToolbarIcon').attr('src',photosInCart ? "${resource(dir:'images', file: 'cart_filled_m.png')}" :  "${resource(dir:'images', file: 'cart_m.png')}" )
	}
}

</script>
